#!/usr/bin/python
#coding=utf-8

from utils.common import import_obj
from utils.common import render 

class Router(object):
    
    def __init__(self):
        self.path_mapper = {}

    def route(self, req, resp):
        path = req.path_info 
        handler_cls = self.path_mapper.get(req.path_info)  
        if not handler_cls:
            resp.status = '404 Not Found'
            body = render('notfound.html')
            return resp.respond(body)
        handler = import_obj(handler_cls)
        try:
             method = req.method
             if method == 'GET':
                 return handler.get(req, resp)
             elif method == 'POST':
                 return handler.post(req, resp)
             elif method == 'PUT':
                 return handler.put(req, resp)
             elif method == 'HEAD':
                 return handler.head(req, resp)
             else:
                 handler.error(req, resp, 501)
        except Exception, e:
            raise e
        return resp.respond()

    def __call__(self, path, handler_cls):  
        self.path_mapper[path] =  handler_cls

    
